﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Wpf.CommonTools.NumberExtension
{
    public static class NumberExtension
    {
        /// <summary>
        /// 将可能为null的int对象的转化为int值(对象必须是int值,否则抛出异常)
        /// </summary>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int ToInt32(this object value, int defaultValue = 0)
        {
            if (value == null)
            {
                return defaultValue;
            }
            else
            {
                int i;
                try
                {
                    i = Convert.ToInt32(value);
                }
                catch
                {
                    i = defaultValue;
                }
                return i;
            }
        }
        /// <summary>
        /// 将可能为null的int对象的转化为long值(对象必须是long值,否则抛出异常)
        /// </summary>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static long ToInt64(this object value, int defaultValue = 0)
        {
            if (value == null)
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToInt64(value);
            }
        }

        /// <summary>
        /// 将字符串转化成int值
        /// 如果为空或者不能转化为Int类型返回0
        /// 不会抛出异常
        /// </summary>
        /// <param name="number"></param>
        /// <param name="returnValue">如果出错返回的值(默认0)</param>
        /// <returns></returns>
        public static int ToInt32(this string number, int returnValue = 0)
        {
            int i;
            bool b = int.TryParse(number, out i);
            return b ? i : returnValue;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <param name="returnValue"></param>
        /// <returns></returns>
        public static double ToDouble(this string number, double returnValue = 0)
        {
            double i;
            bool b = double.TryParse(number, out i);
            return b ? i : returnValue;
        }
        /// <summary>
        /// 将字符串转化成int64值
        /// </summary>
        /// <param name="number"></param>
        /// <param name="returnValue">如果出错返回的值(默认0)</param>
        /// <returns></returns>
        public static long ToInt64(this string number, long returnValue = 0)
        {
            long i;
            bool b = long.TryParse(number, out i);
            return b ? i : returnValue;
        }

    }
}
